package com.tos.quran;

import java.io.File;

import android.app.Application;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.StatFs;

public class QuranApp extends Application {

	public static final File ROOT = Environment.getExternalStorageDirectory();

	private static final String KEY_IS_ON_SDCARD = "KEY_IS_ON_SDCARD";
	private SharedPreferences sharedPreferences;
	private boolean isOnSdCard;

	private void initSharedPreference() {
		try {
			if (sharedPreferences == null) {
				sharedPreferences = getSharedPreferences("APP_MODE",
						MODE_PRIVATE);
				isOnSdCard = sharedPreferences.getBoolean(KEY_IS_ON_SDCARD,
						true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setOnSdCard(boolean isOnSdCard) {
		initSharedPreference();
		this.isOnSdCard = isOnSdCard;
		sharedPreferences.edit().putBoolean(KEY_IS_ON_SDCARD, isOnSdCard)
				.commit();
	}

	public boolean isOnSdCard() {
		initSharedPreference();
		return isOnSdCard;
	}

	@Override
	public File getDatabasePath(String name) {
		File file = null;
		try {
			initSharedPreference();
			if (isOnSdCard) {
				String packageName = getPackageName();
				File path = new File(ROOT, packageName.substring(packageName
						.lastIndexOf('.') + 1) + File.separator);

				file = new File(path, name);
				if ((!file.exists()) && (getExternalAvailableSpaceInMB() < 20)) {
					file = super.getDatabasePath(name);
				} else if (!path.exists()) {
					path.mkdirs();
				}
			} else {
				file = super.getDatabasePath(name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}

	public final static long SIZE_KB = 1024L;
	public final static long SIZE_MB = SIZE_KB * SIZE_KB;

	public long getExternalAvailableSpaceInMB() {
		return getExternalAvailableSpaceInBytes() / SIZE_MB;
	}

	public static long getExternalAvailableSpaceInBytes() {
		long availableSpace = -1L;
		try {
			StatFs stat = new StatFs(ROOT.getPath());
			availableSpace = (long) stat.getAvailableBlocks()
					* (long) stat.getBlockSize();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return availableSpace;
	}
}
